package com.supply.hsa.link.task.fetch.process;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.supply.hsa.link.common.constant.SupplierClass;
import com.supply.hsa.link.task.fetch.hotel.container.ThreadPoolContainer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

@Service
@Slf4j
public class ThreadPoolConfig {
	@Autowired
	private ThreadPoolContainer threadPoolContainer;
	
	private Map<SupplierClass, Integer> oldThreadPoolMap = new HashMap<SupplierClass, Integer>();
	
	private String fetchThreadPoolJson;

	public String getFetchThreadPoolJson() {
		return fetchThreadPoolJson;
	}

	public void setFetchThreadPoolJson(String fetchThreadPoolJson) {
		this.fetchThreadPoolJson = fetchThreadPoolJson;
	}
	
	@SuppressWarnings("unchecked")
	public Map<SupplierClass, Integer> getFetchThreadPool(){
		String json = this.getFetchThreadPoolJson();
		if(StringUtils.isBlank(json)){
			return Collections.emptyMap();
		}
		
		Map<String, Integer> jsonMap = JSON.parseObject(json, Map.class);
		if(MapUtils.isEmpty(jsonMap)){
			return Collections.emptyMap();
		}
		
		Map<SupplierClass, Integer> threadPoolMap = new HashMap<SupplierClass, Integer>();
		for(Map.Entry<String, Integer> entry : jsonMap.entrySet()){
			SupplierClass supplierClass = SupplierClass.getSupplierClass(entry.getKey());
			
			if(supplierClass == null){
				continue;
			}
			
			int poolSize = 0;
			if(entry.getValue()<=0 || entry.getValue()>50){
				poolSize = ThreadPoolContainer.FETCH_THREAD_POOL_SIZE;
			}else{
				poolSize = entry.getValue();
			}
			
			threadPoolMap.put(supplierClass, poolSize);
		}
		
		return threadPoolMap;
	}
}
